package com.fzu.commonutil.util;


import com.alibaba.fastjson.JSON;
import lombok.Data;

import java.io.Serializable;
import java.util.Map;

/**
 * 同一返回类
 * @author IT00ZYQ
 * @date 2021/4/5 12:32
 **/
@Data
public class R implements Serializable {

    private Boolean success;
    private Integer code;
    private String message;
    private Object data;

    private R(){}

    /**
     * 成功静态方法
     */
    public static R ok(){
        R r = new R();
        r.setSuccess(true);
        r.setCode(200);
        r.setMessage("成功");
        return r;
    }

    /**
     * 失败静态方法
     */
    public static R error() {
        R r = new R();
        r.setSuccess(false);
        r.setCode(500);
        r.setMessage("失败");
        return r;
    }

    /**
     * 失败静态方法
     */
    public static R error(ErrorEnum errorEnum) {
        R r = new R();
        r.setSuccess(false);
        r.setCode(errorEnum.getCode());
        r.setMessage(errorEnum.getMessage());
        return r;
    }

    /**
     * 下面四个方法返回this指针是为了实现链式编程
     */

    public R message(String message){
        this.setMessage(message);
        return this;
    }

    public R code(Integer code){
        this.setCode(code);
        return this;
    }

    public R data(Object value){
        this.data = value;
        return this;
    }

    public R data(Map<String, Object> map){
        this.setData(map);
        return this;
    }

    @SuppressWarnings("all")
    public static Object getDataFromR(R r, Class c) {
        Integer code = r.getCode();
        String message = r.getMessage();
        if (!code.equals(200)) {
            throw new ApiException(code, message);
        }
        if (r.getData() == null) {
            throw new ApiException(ErrorEnum.OBJECT_NOT_FOUND);
        }
        return JSON.parseObject(JSON.toJSONString(r.getData()), c);
    }

}
